package com.itheima.dubbo.api;

import com.itheima.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /*保存访客，每个访客每天只保存一条数据*/
    @Override
    public void save(Visitors visitors) {
        //先判断是否存在，不存在就保存
        boolean exists = mongoTemplate.exists(Query.query(Criteria.where("userId").is(visitors.getUserId()).and("visitorUserId").is(visitors.getVisitorUserId()).and("visitDate").is(visitors.getVisitDate())), Visitors.class);
        //不存在就保存
        if (!exists) {
            mongoTemplate.save(visitors);
        }
    }

    @Override
    public List<Visitors> queryVisitors(Long userId, Long date) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (date != null) {
            criteria.and("date").gt(date);
        }
        return mongoTemplate.find(Query.query(criteria).with(Sort.by(Sort.Order.desc("date"))).limit(5), Visitors.class);
    }
}
